<template>

  <div class="main-content-flex">
    <div class="main-content-left">
      <div class="welcome-card minimal">
        <div class="welcome-main-v2 minimal">
          <div class="welcome-title-big minimal">欢迎回来！</div>
          <div class="welcome-subrow minimal">
            <span class="welcome-label minimal">上次模拟：</span>
            <span class="welcome-type minimal">{{ latestInterviewType }}</span>
          </div>
        </div>
        <button class="report-btn-v2 minimal" @click="viewReport"><i class="fa fa-bar-chart"></i> 分析报告</button>
      </div>
      <div class="charts">
        <div class="chart-box">
          <div class="chart-title"><i class="fa fa-shield"></i> <span class="highlight-eval">专业能力评估</span></div>
          <div ref="radarProfessional" class="chart-content"></div>
        </div>
        <div class="chart-box">
          <div class="chart-title"><i class="fa fa-line-chart"></i> 能力变化趋势</div>
          <div ref="lineProfessional" class="chart-content"></div>
        </div>
      </div>
      <div class="contribution">
        <div style="margin-top:16px;">
          <div ref="calendarChart" style="width:100%;height:320px;"></div>
        </div>
      </div>
    </div>
    <div class="main-content-right">
      <RightCard />
    </div>
  </div>
</template>

<script>

import request from '@/utils/request'
import * as echarts from 'echarts'
import { getProfessionalAbilityList } from '@/api/example/ability'
import { getInterviewRecordList } from '@/api/example/interviewrecord'
import RightCard from './RightCard.vue'

export default {
  name: 'MainContent',
  components: { RightCard },
  data() {
    return {
      // 专业能力指标
      radarIndicatorsProfessional: [
        { name: '前沿知识与理论理解', max: 100 },
        { name: '解决问题能力', max: 100 },
        { name: '合作和沟通能力', max: 100 },
        { name: '项目经验', max: 100 },
        { name: '编程与工程', max: 100 },
        { name: '基础知识', max: 100 }
      ],
      radarDataProfessional: [0, 0, 0, 0, 0, 0],
      radarDataProfessionalLatest: [0, 0, 0, 0, 0, 0],
      trendLabels: [],
      trendDataProfessional: [0, 0, 0, 0, 0, 0],
      tableData: [],
      pagination: { page: 1, pageSize: 1000000, total: 0 },
      userid: this.$store.getters.userId,
      latestInterviewType: '暂无记录',
    }
  },
  mounted() {
    this.fetchLatestReport();
    this.fetchProfessionalAbility();
    this.fetchData();
    this.initCalendarChart();
    this.fetchLatestInterview();
    window.addEventListener('resize', this.handleResize);
    },
  methods: {
    async fetchLatestReport() {
      try {
        const res = await request({
          url: '/api/example/Whu_report/getList',
          method: 'post',
          data: {
            page: 1,
            pageSize: 1,
            sidx: 'date',
            sord: 'desc',
          }
        })
        if (res && res.data && res.data.list && res.data.list.length) {
          const latestReport = res.data.list[0]
          console.log('最新报告:', latestReport)
          console.log(res.data.list)
          this.latestReport = latestReport
        }
      } catch (error) {
        console.error('获取最新报告失败:', error)
      }
    },
    // 专业能力
    fetchProfessionalAbility() {
      getProfessionalAbilityList({
        currentPage: 1,
        pageSize: 100,
      }).then(res => {
        const list = (res.data && res.data.list) ? res.data.list : []
        const abilityNames = this.radarIndicatorsProfessional.map(ind => ind.name)
        const abilityMap = {}
        abilityNames.forEach(name => { abilityMap[name] = [] })
        const timeSet = new Set()
        list.forEach(item => {
          timeSet.add(item.time)
          if (abilityMap[item.type]) {
            abilityMap[item.type].push({ time: item.time, score: Number(item.score) || 0 })
          }
        })
        // 平均分
        this.radarDataProfessional = abilityNames.map(name => {
          const arr = abilityMap[name].map(i => i.score)
          if (!arr.length) return 0
          return Math.round(arr.reduce((a, b) => a + b, 0) / arr.length)
        })
        // 最近一次分数
        this.radarDataProfessionalLatest = abilityNames.map(name => {
          const arr = abilityMap[name]
          if (!arr.length) return 0
          arr.sort((a, b) => new Date(b.time) - new Date(a.time))
          return arr[0].score
        })
        // 折线图：每种能力一条线，横坐标为time
        let timeList = Array.from(timeSet).sort((a, b) => new Date(a) - new Date(b))
        // 只保留最近十条
        if (timeList.length > 10) {
          timeList = timeList.slice(-10)
        }
        this.trendLabels = timeList
        const series = abilityNames.map(name => {
          const scoreMap = {}
          abilityMap[name].forEach(i => { scoreMap[i.time] = i.score })
          return {
            name,
            type: 'line',
            data: timeList.map(time => scoreMap[time] !== undefined ? scoreMap[time] : 0),
          }
        })
        this.initLineProfessional(timeList, series)
        this.initRadarProfessional()
      })
    },
    // 专业能力评估雷达图（极简风格，平均分虚线，最近一次实线）
    initRadarProfessional() {
      const chart = echarts.init(this.$refs.radarProfessional)
      chart.setOption({
        tooltip: { show: true, backgroundColor: '#fff', borderColor: '#eee', textStyle: { color: '#444' } },
        radar: {
          indicator: this.radarIndicatorsProfessional,
          splitNumber: 4,
          radius: '70%',
          axisName: {
            color: '#666',
            fontWeight: 400,
            fontSize: 13,
            padding: [2, 4]
          },
          splitArea: {
            areaStyle: {
              color: ['#faf8f2', '#f5f5f5', '#fff']
            }
          },
          splitLine: {
            lineStyle: {
              color: '#e0e0e0',
              width: 1
            }
          },
          axisLine: {
            lineStyle: {
              color: '#e0e0e0',
              width: 1
            }
          }
        },
        legend: {
          data: ['平均分', '最近一次'],
          top: 20,
          right: 10,
          icon: 'circle',
          itemWidth: 10,
          itemHeight: 10,
          textStyle: { color: '#888', fontWeight: 400, fontSize: 13 }
        },
        series: [
          {
            name: '平均分',
            type: 'radar',
            symbol: 'circle',
            symbolSize: 6,
            lineStyle: {
              color: '#bdbdbd',
              width: 2,
              type: 'dashed'
            },
            itemStyle: {
              color: '#bdbdbd',
              borderColor: '#fff',
              borderWidth: 1
            },
            areaStyle: {
              color: 'rgba(189,189,189,0.05)'
            },
            data: [
              { value: this.radarDataProfessional, name: '平均分' }
            ]
          },
          {
            name: '最近一次',
            type: 'radar',
            symbol: 'circle',
            symbolSize: 6,
            lineStyle: {
              color: '#ffb347',
              width: 2,
              type: 'solid'
            },
            itemStyle: {
              color: '#ffb347',
              borderColor: '#fff',
              borderWidth: 1
            },
            areaStyle: {
              color: 'rgba(255,179,71,0.07)'
            },
            data: [
              { value: this.radarDataProfessionalLatest, name: '最近一次' }
            ]
          }
        ]
      })
      this.radarProfessionalChart = chart
    },
    // 专业能力变化趋势折线图（6种好区分的颜色）
    initLineProfessional(xAxisData = [], series = []) {
      const colorList = [
        '#ffe0b2', '#fff9c4', '#b3e5fc',
        '#c8e6c9', '#e1bee7', '#ffccbc'
      ];
      const chart = echarts.init(this.$refs.lineProfessional);
      chart.setOption({
        tooltip: { trigger: 'axis', backgroundColor: '#fff', borderColor: '#eee', textStyle: { color: '#444' } },
        legend: {
          data: this.radarIndicatorsProfessional.map(i => i.name),
          top: '10px', // 图例置顶，避免压图表
          right: '10px',
          icon: 'circle',
          itemWidth: 10,
          itemHeight: 10,
          textStyle: { color: '#888', fontWeight: 400, fontSize: 13 }
        },
        grid: {
          left: '36px',
          right: '36px',
          top: '70px', // 增大顶部间距，给图例和坐标轴文字留空间
          bottom: '32px'
        },
        xAxis: {
          type: 'category',
          data: xAxisData,
          name: '',
          axisLine: { lineStyle: { color: '#e0e0e0', width: 1 } },
          axisLabel: {
            color: '#888',
            fontWeight: 400,
            fontSize: 13,
            margin: 8 // 增大坐标轴文字与轴线的间距
          },
          splitLine: { show: false }
        },
        yAxis: {
          type: 'value',
          max: 100,
          axisLine: { lineStyle: { color: '#e0e0e0', width: 1 } },
          axisLabel: {
            color: '#888',
            fontWeight: 400,
            fontSize: 13
          },
          splitLine: { lineStyle: { color: '#f5f5f5', width: 1 } }
        },
        series: (series.length ? series : [{
          name: '专业能力',
          type: 'line',
          data: this.trendDataProfessional,
        }]).map((s, idx) => ({
          ...s,
          smooth: true,
          symbol: 'circle',
          symbolSize: 6,
          lineStyle: {
            color: colorList[idx % colorList.length],
            width: 2
          },
          itemStyle: {
            color: colorList[idx % colorList.length],
            borderColor: '#fff',
            borderWidth: 1
          },
          areaStyle: {
            color: colorList[idx % colorList.length] + '22'
          }
        }))
      });
      this.lineProfessionalChart = chart;
    },
    viewReport() {
      if (this.latestReport && this.latestReport.analysis) {
      window.open(this.latestReport.analysis, '_blank');
    } else {
      this.$message.warning('暂无最新分析报告');
    }
    },
    fetchData() {
      getInterviewRecordList({
        page: this.pagination.page,
        pageSize: this.pagination.pageSize,
        userid: this.userid
      }).then(res => {
        const data = res.data || {}
        this.tableData = (Array.isArray(data.list) ? data.list : []).map(item => {
          // 处理 JSON 格式的场景数据
          if (item.scene && item.scene.startsWith('[')) {
            try {
              item.scene = JSON.parse(item.scene).join('、')
            } catch (e) {
              console.error('解析场景数据失败:', e)
            }
          }

          // 处理带引号的字符串数据
          ['type', 'style'].forEach(key => {
            if (item[key] && typeof item[key] === 'string' && item[key].startsWith('"')) {
              try {
                item[key] = JSON.parse(item[key])
              } catch (e) {
                console.error(`解析${key}数据失败:`, e)
              }
            }
          })

          // 处理空值显示
          Object.keys(item).forEach(key => {
            if (item[key] === null || item[key] === '') {
              item[key] = '-'
            }
          })

          return item
        })

        this.updateCalendarChart()
      })
    },
    typeFormatter(row) {
      if (row.intype === '1') return '模拟面试'
      if (row.intype === '0') return '练习'
      if (row.intype === '-') return '-'
      return row.intype || '-'
    },
    getCalendarData(year) {
      const map = {}
      this.tableData.forEach(item => {
        if (item.todate && item.todate !== '-') {
          // 提取日期部分 (YYYY-MM-DD)
          const date = item.todate.split(' ')[0]
          map[date] = (map[date] || 0) + 1
        }
      })

      // 生成全年数据
      const date = new Date(`${year}-01-01`).getTime()
      const end = new Date(`${year + 1}-01-01`).getTime()
      const dayTime = 3600 * 24 * 1000
      const data = []

      for (let time = date; time < end; time += dayTime) {
        const d = new Date(time)
        const dStr = [
          d.getFullYear(),
          String(d.getMonth() + 1).padStart(2, '0'),
          String(d.getDate()).padStart(2, '0')
        ].join('-')
        data.push([dStr, map[dStr] || 0])
      }

      return data
    },
    initCalendarChart() {
      this.$nextTick(() => {
        if (!this.$refs.calendarChart) return
        if (!this.calendarChart) {
          this.calendarChart = echarts.init(this.$refs.calendarChart)
        }
        this.setCalendarOption()
      })
    },
    updateCalendarChart() {
      if (this.calendarChart) {
        this.setCalendarOption()
      }
    },
    setCalendarOption() {
      const year = new Date().getFullYear();
      const data = this.getCalendarData(year);

      // 计算最大值，用于动态调整颜色范围
      const maxValue = Math.max(...data.map(item => item[1]), 10);

      this.calendarChart.setOption({
        title: {
          top: 20,
          left: 'center',
          text: `${year}年面试日历`,
          textStyle: {
            color: '#582d01', // 与页面标题颜色一致
            fontSize: 18,
            fontWeight: 'bold'
          }
        },
        tooltip: {
          formatter: function(params) {
            const value = params.value[1];
            const date = params.value[0];
            return `
              <div style="font-weight:bold;margin-bottom:5px;">${date}</div>
              <div>面试次数: <span style="font-weight:bold;color:#ffb347">${value}</span></div>
            `;
          }
        },
        visualMap: {
          min: 0,
          max: maxValue,
          type: 'piecewise',
          orient: 'horizontal',
          left: 'center',
          top: 60,
          textStyle: {
            color: '#582d01' // 与页面标题颜色一致
          },
          inRange: {
            color: ['#ebedf0', '#c6e48b', '#7bc96f', '#239a3b', '#196127']
          },
          pieces: [
            {min: 0, max: 0, color: '#ebedf0', label: '无记录'},
            {min: 1, max: 1, color: '#c6e48b', label: '1次'},
            {min: 2, max: 3, color: '#7bc96f', label: '2-3次'},
            {min: 4, max: 5, color: '#239a3b', label: '4-5次'},
            {min: 5.5, color: '#196127', label: '6次+'}
          ]
        },
        calendar: {
          top: 100,
          left: 20,
          right: 20,
          cellSize: ['auto', 15],
          range: year,
          itemStyle: {
            borderWidth: 1,
            borderColor: '#f7f5f0' // 与背景色一致
          },
          dayLabel: {
            color: '#582d01', // 与页面标题颜色一致
            fontSize: 12
          },
          monthLabel: {
            color: '#582d01', // 与页面标题颜色一致
            fontSize: 12,
            nameMap: 'cn'
          },
          yearLabel: {
            show: false
          }
        },
        series: {
          type: 'heatmap',
          coordinateSystem: 'calendar',
          data: data,
          emphasis: {
            itemStyle: {
              shadowBlur: 10,
              shadowColor: 'rgba(0, 0, 0, 0.5)'
            }
          },
          label: {
            show: true,
            formatter: function(params) {
              return params.value[1] > 0 ? params.value[1] : '';
            },
            color: '#fff',
            fontSize: 10
          }
        }
      });
    },
    handleResize() {
      if (this.calendarChart) {
        this.calendarChart.resize();
      }
    },
    async fetchLatestInterview() {
      try {
        const res = await getInterviewRecordList({
          page: 1,
          pageSize: 1000, 
          userid: this.userid 
        })

        if (res.data && res.data.list && res.data.list.length) {
          // 在前端按 todate 降序排序
          const sortedList = [...res.data.list].sort((a, b) => {
            const dateA = new Date(a.todate || 0)
            const dateB = new Date(b.todate || 0)
            return dateB - dateA // 降序排列
          })
          this.latestInterviewType = sortedList[0].type || '未知岗位'
          console.log('最新面试记录:', sortedList)
          return sortedList[0] // 返回最新的记录
        }

        return null
      } catch (error) {
        console.error('获取最新面试记录失败:', error)
        return null
      }
    },
  },
  beforeDestroy() {
    if (this.radarProfessionalChart) this.radarProfessionalChart.dispose()
    if (this.lineProfessionalChart) this.lineProfessionalChart.dispose()
     window.removeEventListener('resize', this.handleResize);
  }
}
</script>

<style scoped>
.main-content-flex {
  display: flex;
  flex-direction: row;
  align-items: flex-start;
  width: 100%;
  box-sizing: border-box;
  gap: 32px;
}
.main-content-left {
  flex: 1 1 0%;
  min-width: 0;
  padding: 20px 0 20px 20px;
  box-sizing: border-box;
}
.main-content-right {
  width: 320px;
  min-width: 260px;
  max-width: 360px;
  box-sizing: border-box;
  padding: 20px 20px 20px 0;
}

.welcome-card.minimal {
  background: none;
  box-shadow: none;
  border-radius: 0;
  padding: 0 0 18px 0;
  margin-bottom: 18px;
  display: flex;
  align-items: flex-end;
  gap: 18px;
  border-bottom: 1.5px solid #ffe082;
}
.welcome-main-v2.minimal {
  display: flex;
  flex-direction: column;
  flex: 1;
  min-width: 0;
}
.welcome-title-big.minimal {
  font-size: 2.1rem;
  font-weight: 800;
  color:  #582d01;
  letter-spacing: 1.5px;
  margin-bottom: 6px;
  line-height: 1.18;
  text-shadow: none;
  white-space: nowrap;
}
.welcome-subrow.minimal {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 1.08rem;
}
.welcome-label.minimal {
  color: inherit;
  font-weight: normal;
  background: none;
  padding: 0;
}
.welcome-type.minimal {
  color: inherit;
  font-weight: normal;
  background: none;
  padding: 0;
  border-radius: 0;
  box-shadow: none;
}
.report-btn-v2.minimal {
  background: #ffcf3f;
  color: #fff;
  border: none;
  padding: 8px 22px;
  border-radius: 10px;
  cursor: pointer;
  font-size: 15px;
  font-weight: 700;
  box-shadow: 0 2px 8px 0 rgba(255, 224, 130, 0.10);
  transition: background 0.18s, color 0.18s, box-shadow 0.18s;
  display: flex;
  align-items: center;
  gap: 8px;
  margin-left: auto;
  letter-spacing: 1px;
}
.report-btn-v2.minimal:hover {
  background: linear-gradient(90deg, #ffd54f 0%, #ffb347 100%);
  color: #fff;
  box-shadow: 0 4px 16px 0 rgba(255, 224, 130, 0.18);
}
.report-btn {
  background: linear-gradient(90deg, #ffb347 0%, #ff7043 100%);
  color: #fff;
  border: none;
  padding: 5px 14px;
  border-radius: 8px;
  cursor: pointer;
  font-size: 14px;
  font-weight: 600;
  box-shadow: 0 2px 8px 0 rgba(255,183,71,0.10);
  transition: all 0.3s cubic-bezier(.4,0,.2,1);
  display: flex;
  align-items: center;
  gap: 6px;
  margin-left: 12px;
}
.report-btn:hover {
  background: linear-gradient(90deg, #ff7043 0%, #ffb347 100%);
}
.charts {
  display: flex;
  gap: 20px;
  margin-bottom: 20px;
}
.chart-item h4 {
  margin: 0 0 10px 0;
  font-size: 14px;
}
.analysis {
  margin-bottom: 20px;
}
.analysis h3 {
  margin: 0 0 10px 0;
  font-size: 16px;
}
.analysis .up {
  color: green;
  margin-right: 20px;
}
.analysis .down {
  color: red;
}
.recommend-resource {
  margin-bottom: 20px;
}
.recommend-resource h3 {
  margin: 0 0 10px 0;
  font-size: 16px;
}
.resource-link {
  color: #007bff;
  text-decoration: none;
  cursor: pointer;
}
.resource-link:hover {
  text-decoration: underline;
}
.contribution {
  margin-bottom: 20px;
}
.contribution h4 {
  margin: 0 0 10px 0;
  font-size: 14px;
}
.contribution-settings {
  margin-bottom: 10px;
}
.learn-text {
  margin: 0;
  font-size: 12px;
  color: #6c757d;
}

.charts {
  display: flex;
  gap: 24px;
  margin-bottom: 20px;
}
.chart-box {
  background: #ffffff;
  border-radius: 8px;
  box-shadow: 0 2px 8px #f0f1f2;
  padding: 16px;
  display: flex;
  flex-direction: column;
  height: 300px;
  flex: 1;
}
.chart-title {
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 8px;
  text-align: center;
  color: #513101;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
}
.chart-title i {
  color: #ffd54f;
  font-size: 18px;
}
.chart-content {
  flex: 1;
  width: 100%;
  height: 95%;
}
[ref="calendarChart"] {
  background: #ffffff; /* 白色背景与卡片一致 */
  border-radius: 8px; /* 与卡片圆角一致 */
  box-shadow: 0 2px 8px #f0f1f2; /* 与卡片阴影一致 */
  padding: 10px;
  transition: all 0.3s;
  margin-top: 16px;
}

[ref="calendarChart"]:hover {
  box-shadow: 0 4px 12px rgba(200, 180, 120, 0.12);
}
</style>


